<template>
  <div class="search-container">
    <!-- 上半部分 -->
    <div class="top-section">
      <!-- 轮播图 -->
      <el-carousel indicator-position="outside" class="banner-carousel">
        <el-carousel-item v-for="item in 3" :key="item">
          <img src="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif" alt="轮播图">
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 下半部分 -->
    <div class="bottom-section">
      <!-- 左边：搜索主体区域 -->
      <div class="search-main">
        <!-- 搜索区域 -->
        <div class="search-section">
          <!-- 已选择过滤项 -->
          <div class="selected-filters">
            <div class="filter-item" v-for="(v, k) in params.filters" :key="k" @click="deleteFilter(k)">
              {{ filterNames[k] }}：{{ v }} <span class="close">×</span>
            </div>
          </div>

          <!-- 过滤条件 -->
          <div class="filters">
            <div v-for="(v, k) in remainFilter" :key="k" class="filter-group">
              <div class="filter-title">{{ filterNames[k] }}</div>
              <div class="filter-options">
                <div class="filter-option" v-for="(o, j) in v" :key="j" @click="clickFilter(k, o)">
                  {{ o }}
                </div>
              </div>
            </div>

            <div class="filter-group">
              <div class="filter-title">价格</div>
              <div class="filter-options">
                <div class="filter-option" @click="clickFilter('price', '0-100')">
                  100元以下
                </div>
                <div class="filter-option" @click="clickFilter('price', '100-300')">
                  100-300元
                </div>
                <div class="filter-option" @click="clickFilter('price', '300-600')">
                  300-600元
                </div>
                <div class="filter-option" @click="clickFilter('price', '600-1500')">
                  600-1500元
                </div>
                <div class="filter-option" @click="clickFilter('price', '1500-0')">
                  1500元以上
                </div>
              </div>
            </div>
          </div>

          <!-- 排序和分页 -->
          <div class="action-bar">
            <div class="sort-options">
              <div class="sort-item" v-for="(item, i) in sortItems" :key="i"
                :class="{ active: params.sortBy === item.key }" @click="changeSort(item.key)">
                {{ item.text }}
              </div>
            </div>

            <!-- 排序方向切换按钮 -->
            <div v-if="params.sortBy !== 'default'" class="sort-direction" @click="toggleSortOrder">
              <el-icon class="sort-icon">
                <SortUp v-if="params.isAsc" />
                <SortDown v-else />
              </el-icon>
            </div>
          </div>

          <!-- 商品列表 -->
          <div class="product-list" v-loading="loading">
            <div class="v-card clickable list-item" v-for="product in productList" :key="product.id"
              @click="showProductDetail(product.id)">
              <div class="hos-item">
                <div class="wrapper">
                  <div class="hospital-title">{{ product.name }}</div>
                  <div class="bottom-container">
                    <div class="icon-wrapper">
                      价格：{{ product.price }}
                    </div>
                    <div class="icon-wrapper">
                      销量: {{ product.sales }}
                    </div>
                  </div>
                </div>
                <img :src="product.imageUrl" :alt="product.name" class="hospital-img">
              </div>
            </div>
          </div>

          <!-- 分页组件 -->
          <div class="pagination">
            <PaginationComponent v-model:current-page="params.page" v-model:page-size="params.size" :total="total"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>

      <!-- 右边：公告通知区域 -->
      <div class="right-sidebar">
        <div class="common-dept">
          <div class="header-wrapper">
            <div class="title">热门分类</div>
            <div class="all-wrapper">
              <span>全部</span>
            </div>
          </div>
          <div class="content-wrapper">
            <span class="item v-link clickable dark" v-for="category in hotCategories" :key="category.id"
              @click="selectCategory(category.name)">
              {{ category.name }}
            </span>
          </div>
        </div>
        <div class="space">
          <div class="header-wrapper">
            <div class="title-wrapper">
              <span class="title">平台公告</span>
            </div>
            <div class="all-wrapper">
              <span>全部</span>
            </div>
          </div>
          <div class="content-wrapper">
            <div class="notice-wrapper" v-for="notice in notices" :key="notice.id">
              <div class="point"></div>
              <span class="notice v-link clickable dark">{{ notice.title }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PaginationComponent from '@/components/PaginationComponent.vue'
import searchAPI from '@/api/search'
import { SortUp, SortDown } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 状态定义
const productList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const searchText = ref(route.query.key || '') // 搜索关键词

// 新增状态
const hotCategories = ref([
  { id: 1, name: '电子产品' },
  { id: 2, name: '服装鞋帽' },
  { id: 3, name: '家居用品' },
  { id: 4, name: '美妆护肤' },
  { id: 5, name: '食品生鲜' },
  { id: 6, name: '图书文具' },
  { id: 7, name: '运动户外' },
  { id: 8, name: '母婴玩具' }
])

const notices = ref([
  { id: 1, title: '小淘商城618大促即将开启，全场5折起' },
  { id: 2, title: '新用户注册即送200元优惠券' },
  { id: 3, title: '夏季清仓特卖，低至1折' }
])

const params = ref({
  key: route.query.key || '',
  pageNo: parseInt(route.query.pageNo) || 1,
  pageSize: parseInt(route.query.pageSize) || 10,
  sortBy: route.query.sortBy || 'default',
  isAsc: true,
  filters: {}
})

// 排序选项
const sortItems = [
  { key: 'default', text: '默认' },
  { key: 'sales', text: '销量' },
  { key: 'price', text: '价格' }
]

// 过滤名称映射
const filterNames = {
  category: '分类',
  brand: '品牌',
  price: '价格'
}

// 获取商品数据
const fetchProducts = async () => {
  try {
    loading.value = true

    // 构造搜索条件
    const searchParams = {
      name: params.value.key,
      pageNo: params.value.pageNo,
      pageSize: params.value.pageSize
    }

    // 处理排序
    if (params.value.sortBy !== 'default') {
      searchParams.sortBy = params.value.sortBy
      searchParams.isAsc = params.value.isAsc
    }

    // 处理过滤条件
    const tags = []
    let minPrice = undefined
    let maxPrice = undefined

    Object.keys(params.value.filters).forEach(key => {
      const value = params.value.filters[key]
      switch (key) {
        case 'category':
          tags.push(value)
          break
        case 'brand':
          tags.push(value)
          break
        case 'price':
          const [min, max] = value.split('-').map(Number)
          minPrice = min || 0
          maxPrice = max || undefined // 0表示无上限
          break
      }
    })

    if (tags.length > 0) {
      searchParams.tags = tags
    }

    if (minPrice !== undefined) {
      searchParams.minPrice = minPrice
    }

    if (maxPrice !== undefined) {
      searchParams.maxPrice = maxPrice
    }

    const response = await searchAPI.searchProducts(searchParams)
    const { records, total: totalCount } = response.data.data

    productList.value = records
    total.value = totalCount
  } catch (error) {
    console.error('搜索商品失败:', error)
  } finally {
    loading.value = false
  }
}

// 商品搜索建议
const querySearchAsync = async (queryString, cb) => {
  if (!queryString.trim()) {
    cb([])
    return
  }

  try {
    const response = await searchAPI.searchProductsByName(queryString)
    const results = response.data.map(item => ({
      value: item.name,
      id: item.id
    }))
    cb(results)
  } catch (error) {
    console.error('搜索建议失败:', error)
    cb([])
  }
}

// 处理选择搜索建议
const handleSelect = (item) => {
  searchText.value = item.value
  params.value.key = item.value
  params.value.pageNo = 1
  updateRoute()
}

// 选择分类
const selectCategory = (category) => {
  params.value.filters = { ...params.value.filters, category }
  params.value.pageNo = 1
  updateRoute()
}

// 显示商品详情
const showProductDetail = (productId) => {
  router.push({
    name: 'item',
    params: { id: productId },
    query: {
      from: 'product_list'
    }
  })
}

// 监听路由变化
watch(
  () => route.query,
  (newQuery) => {
    params.value.key = newQuery.key || ''
    params.value.pageNo = parseInt(newQuery.pageNo) || 1
    params.value.pageSize = parseInt(newQuery.pageSize) || 10
    params.value.sortBy = newQuery.sortBy || 'default'
    searchText.value = newQuery.key || ''
    fetchProducts()
  }
)

// 生命周期钩子
onMounted(() => {
  fetchProducts()
})

// 计算属性
const totalPage = computed(() => Math.ceil(total.value / params.value.pageSize))

// 分页方法
const handleSizeChange = (val) => {
  params.value.pageSize = val
  params.value.pageNo = 1
  updateRoute()
}

const handleCurrentChange = (val) => {
  params.value.pageNo = val
  updateRoute()
}

// 排序方法
const changeSort = (sortBy) => {
  const oldSortBy = params.value.sortBy
  params.value.sortBy = sortBy
  // 只有在切换到非默认排序时才默认升序
  if (sortBy !== 'default' && oldSortBy !== sortBy) {
    params.value.isAsc = true
  }
  params.value.pageNo = 1
  updateRoute()
}

// 添加切换排序顺序的方法
const toggleSortOrder = () => {
  params.value.isAsc = !params.value.isAsc
  params.value.pageNo = 1
  updateRoute()
  fetchProducts()
}

// 过滤方法
const clickFilter = (key, value) => {
  params.value.filters = { ...params.value.filters, [key]: value }
  params.value.pageNo = 1
  updateRoute()
}

const deleteFilter = (key) => {
  const newFilters = { ...params.value.filters }
  delete newFilters[key]
  params.value.filters = newFilters
  params.value.pageNo = 1
  updateRoute()
}

const remainFilter = computed(() => {
  // 根据实际业务逻辑返回剩余的过滤选项
  return {
    category: ['科技', '穿搭', '美食', '运动', '户外', '护肤'],
    brand: ['小米', '华为', 'OPPO', '苹果']
  }
})

// 更新路由参数
const updateRoute = () => {
  router.push({
    name: 'search',
    query: {
      key: params.value.key,
      pageNo: params.value.pageNo.toString(),
      pageSize: params.value.pageSize.toString(),
      sortBy: params.value.sortBy,
      ...Object.keys(params.value.filters).reduce((acc, key) => {
        acc[`filter_${key}`] = params.value.filters[key]
        return acc
      }, {})
    }
  })
}
</script>

<style scoped>
.search-container {
  padding: 1rem;
  background-color: #f0f8ff;
  display: flex;
  flex-direction: column;
  position: relative;
  width: calc(100% - 2rem);
}

.top-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.banner-carousel {
  width: 100%;
  max-width: 1000px;
  margin-bottom: 1rem;
}

.banner-carousel img {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.bottom-section {
  display: flex;
  width: 100%;
}

.search-main {
  flex: 1;
  margin-right: 2rem;
}

.search-section {
  max-width: 100%;
  margin: 0 auto;
  padding: 1rem;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-wrapper {
  margin: 1rem 0;
  display: flex;
  width: 70%;
}

.search-input {
  flex: 1;
}

.search-btn {
  padding: 10px 20px;
  background: #409EFF;
  color: white;
  cursor: pointer;
  border-radius: 0 4px 4px 0;
}

.selected-filters {
  display: flex;
  flex-wrap: wrap;
  margin: 1rem 0;
  padding: 0 1rem; /* 增加内边距 */
}

.filter-item {
  background: #e6f7ff;
  padding: 0.3rem 0.6rem;
  margin: 0.3rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  color: #1c3d5a;
}

.filter-item .close {
  margin-left: 0.5rem;
  color: #999;
}

.filters {
  margin: 1rem 0;
  padding: 0 1rem; /* 增加内边距 */
}

.filter-group {
  margin-bottom: 1rem;
}

.filter-title {
  font-weight: bold;
  margin-bottom: 0.5rem;
  font-size: 1rem;
  color: #1c3d5a;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
}

.filter-option {
  padding: 0.4rem 0.8rem;
  margin: 0.3rem;
  background: #e6f7ff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  color: #1c3d5a;
}

.filter-option:hover {
  background: #d1e8ff;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 1rem 0;
  padding: 0 1rem; /* 增加内边距 */
}

.sort-options {
  display: flex;
  gap: 1rem;
}

.sort-item {
  padding: 0.4rem 0.8rem;
  cursor: pointer;
  border-radius: 4px;
  background: #e6f7ff;
  color: #1c3d5a;
  transition: all 0.3s ease;
}

.sort-item.active {
  background: #409EFF;
  color: white;
}

.sort-item:hover {
  background: #409EFF;
  color: white;
}

.sort-direction {
  cursor: pointer;
  padding: 0.4rem 0.8rem;
  border-radius: 4px;
  background: #e6f7ff;
  color: #1c3d5a;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.sort-direction:hover {
  background: #409EFF;
  color: white;
}

.sort-icon {
  font-size: 1.2rem;
}

.pagination {
  margin-top: 20px;
  font-size: 0.9rem;
  color: #1c3d5a;
}

.pagination a {
  margin: 0 0.5rem;
  text-decoration: none;
  color: #add8e6;
}

/* 修改商品卡片样式 */
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* 调整为250px */
  gap: 1rem;
  margin-top: 1rem;
  padding: 0 1rem; /* 增加内边距 */
  background-color: white;
}

.list-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
}

.list-item:hover {
  transform: translateY(-5px);
}

.hos-item {
  display: flex;
  padding: 20px;
}

.wrapper {
  flex: 1;
}

.hospital-title {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 10px;
  color: #333;
}

.bottom-container {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.icon-wrapper {
  font-size: 0.9rem;
  color: #666;
}

.hospital-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-left: 10px;
}

.right-sidebar {
  width: 280px;
}

.common-dept,
.space {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.title {
  font-weight: bold;
  font-size: 1.1rem;
}

.all-wrapper {
  color: #409EFF;
  cursor: pointer;
  font-size: 0.9rem;
}

.content-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.item {
  padding: 5px 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 0.9rem;
}

.notice-wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.point {
  width: 6px;
  height: 6px;
  background: #409EFF;
  border-radius: 50%;
  margin-right: 10px;
}

.notice {
  font-size: 0.9rem;
  color: #666;
  flex: 1;
}

/* 响应式布局 */
@media (min-width: 992px) {
  .search-container {
    flex-direction: column;
  }

  .search-section {
    max-width: calc(100% - 300px);
  }
}
</style>